package personal

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/models"
	"FromNowOnPromote/博客系统/Tblog/models/User"
	"FromNowOnPromote/博客系统/Tblog/redis"
)

//获取用户个人资料
type GetUserInfo struct {
	controllers.MainController
}

func (this *GetUserInfo) Get() {
	token := this.Ctx.GetCookie("uuid")
	body := map[string]interface{}{"code": 300, "data": "验证失败", "msg": "系统错误"}
	if token == "" {
		body = map[string]interface{}{"code": 300, "data": "验证失败", "msg": "用户无效"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	} else {
		rd := redis.R.Conn
		id, err1 := rd.Get(token)
		defer rd.Close()
		if err1 != nil {
			body = map[string]interface{}{"code": 301, "data": "验证失败", "msg": "用户无效"}
			this.Data["json"] = body
			this.ServeJSON()
			return
		} else {
			user := User.TbUser{}
			db := models.ConnDb()
			defer db.Close()
			err2 := db.Where("Uuid = ?", id).Find(&user).Error
			if err2 != nil {
				body = map[string]interface{}{"code": 302, "data": "验证失败", "msg": "查询失败"}
				this.Data["json"] = body
				this.ServeJSON()
				return
			} else {
				//将日期格式化为字符串
				b := user.Birthday
				bir := b.Format("2006-01-01")
				body = map[string]interface{}{"code": 200, "data": "验证成功",
					"userInfo": map[string]interface{}{
						"username": user.Username, "sex": user.Sex, "introduce": user.Introduction, "email": user.Email, "birthday": bir, "address": user.Address, "authorImg": user.IconUrl}}
				this.Data["json"] = body
				this.ServeJSON()
				return
			}
		}
	}

}

//删除用户token
type DelToken struct {
	controllers.MainController
}

func (this *DelToken) Get() {
	uuid := this.Ctx.GetCookie("uuid")
	rd := redis.R.Conn
	_, err := rd.Del(uuid)
	if err != nil {
		body := map[string]interface{}{"code": 300, "msg": "操作失败"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	defer rd.Close()
	body := map[string]interface{}{"code": 200, "msg": "用户token已经删除"}
	this.Data["json"] = body
	this.ServeJSON()
}
